
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanxiang_app/bean/detai_new_entity.dart';
import 'package:wanxiang_app/bean/detail_config_entity.dart';
import 'package:wanxiang_app/bean/detail_im_entity.dart';
import 'package:wanxiang_app/bean/goods_detail_entity.dart';
import 'package:wanxiang_app/bean/group_entity.dart';
import 'package:wanxiang_app/bean/im_list_entity.dart';
import 'package:wanxiang_app/bean/process_entity.dart';
import 'package:wanxiang_app/bean/service_list_entity.dart';
import 'package:wanxiang_app/bean/simple_entity.dart';
import 'package:wanxiang_app/pages/home/kanjia.dart';
import 'package:wanxiang_app/pages/msg/chat.dart';
import 'package:wanxiang_app/pages/my/charge.dart';
import 'package:wanxiang_app/pages/my/ordersBuy.dart';
import 'package:wanxiang_app/pages/my/realName.dart';
import 'package:wanxiang_app/utils/common.dart';
import 'package:wanxiang_app/utils/constant.dart';
import 'package:wanxiang_app/utils/user_util.dart';
import 'package:wanxiang_app/widgets/img_dialog.dart';
import '../../bean/config_entity.dart';
import '../../bean/im_entity.dart';
import '../../bean/msg_new_service_entity.dart';
import '../../bean/recrod_ids_entity.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../widgets/detail_appbar.dart';
import '../../widgets/gallery_dialog.dart';
import '../../widgets/myappbar.dart';
import 'package:get/get.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import '../../widgets/simple_dialog.dart';
import 'package:flutter/services.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:http/http.dart' as http;

class DetailController extends GetxController{

  @override
  void onInit() {
    super.onInit();
    _getGoodInfoImg();
  }

  @override
  void onReady() {
    super.onReady();
    Map map = Get.arguments;
    title = map['title'];
    if(map['channel_name']!=null){
      channel_name = map['channel_name'];
    }
    goods_id = map['goods_id'];
    if(map['record_id']!=null){
      record_id = map['record_id'];
      if(map['status']!=null){
        status= map['status'];
      }

    }

    _getService();
    _getServiceList('fqkf');
    _getServiceList('zxkf');
    _getServiceList('ljgm');
    _showBtn();
  }
  @override
  void onClose() {
    super.onClose();
  }
  String record_id = '';
  String status = "";
  String title = '';
  String channel_name = '';
  String goods_id = '';
  int nowClick = 0;
  bool isOpenMore = false;
  bool isEmpty = false;
  late GoodsDetailData detailData;
  var baopeiRate = 0.1.obs;
  bool isInital = false;
  void _getService(){
    Map map = {
      "channel_name":channel_name,
      "goods_id":goods_id,
      "status":status,
      "user_name":UserUtil.getUSER()?.userName
    };
    if(channel_name.isEmpty){
      map = {
        "channel_id":record_id,
        "goods_id":goods_id,
        "status":status,
        "user_name":UserUtil.getUSER()?.userName
      };
    }else{
    }
    DioManager.getInstance().post(ServiceUrl.goodsDetail,map, (data) async {
      GoodsDetailEntity bannerEntity = GoodsDetailEntity.fromJson(jsonDecode(data));
      detailData = bannerEntity.data;
      if(bannerEntity.code!=200){
        isEmpty = true;
        ToastUtil.show(bannerEntity.msg);
        update();
        return;
      }
      channel_name = detailData.channelName;
      _getProcess();
      _getGroup();
      String recordss = UserUtil.getRecord();
      List oldList=[];
      if(recordss.isNotEmpty){
        oldList = json.decode(recordss);
      }
      for(var item in oldList){
        if(item['channelId'] == record_id && item['id'] ==detailData.goodGuid ){
          oldList.remove(item);
          break;
        }
      }
      oldList.insert(0, {
        'channelId':record_id,
        'id':detailData.goodGuid
      });
      recordss = json.encode(oldList);

      UserUtil.saveRecord(recordss);
      isInital = true;
      _getImList();
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  List processData = [];
  // late ProcessData clickProcessItem;
  late Map clickProcessItem;
  void _getProcess(){
    DioManager.getInstance().post(ServiceUrl.process,{
      "channel_name":channel_name,
    }, (data) async {
      // ProcessEntity bannerEntity = ProcessEntity.fromJson(jsonDecode(data));
      Map<String, dynamic> map = json.decode(data);
      processData = map['data'];

      // processData = bannerEntity.data;
      clickProcessItem = processData[0];
    }, (error) {
      ToastUtil.show(error);
    });
  }


  List<DetailImData> imList = [];
  void _getImList() async{
    Uri urls = Uri.https(Constant.baseUrlIm,ServiceUrl.getImByAccount,{'game':record_id,'is_use':'1'});
    var response = await http.get(urls, headers: <String, String>{
      "appKey":Constant.appKey
    },
    );
    var parsedJson = json.decode(response.body);
    DetailImEntity blackEntity =DetailImEntity.fromJson(jsonDecode(parsedJson));

    List<DetailImData> list1 = [];
    List<DetailImData> list2 = [];
    for(var item in blackEntity.data){
      if(item.isHidden!=1){
        if(item.isRest==0){
          list1.add(item);
        }else{
          list2.add(item);
        }
      }

    }
    imList=[];
    imList.addAll(list1);
    imList.addAll(list2);

  }

  List<GroupData> groupData = [];
  void _getGroup(){
    DioManager.getInstance().post(ServiceUrl.qqGroup,{
      "channel_name":channel_name,
    }, (data) async {
      GroupEntity bannerEntity = GroupEntity.fromJson(jsonDecode(data));
      groupData = bannerEntity.data;
    }, (error) {
      ToastUtil.show(error);
    });
  }
  String xuzhi = '';
  void _getGoodInfoImg(){
    DioManager.getInstance().post(ServiceUrl.getGoodInfoImg,{
    }, (data) async {
      SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
      xuzhi = bannerEntity.data;
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }


  void _goodsCollect(){
    DioManager.getInstance().post(ServiceUrl.goodsCollect,{
      "channel_name":channel_name,
      "goods_id":detailData.id.toString(),
      "user_id":UserUtil.getUSER()?.id.toString(),
      "type":detailData.isShoucang?'0':'1'
    }, (data) async {
      SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
      ToastUtil.show(bannerEntity.msg);
      if(bannerEntity.code==200){
        _getService();
      }
    }, (error) {
      ToastUtil.show(error);
    });
  }

  String isKj = '1';
  void _showBtn(){
    DioManager.getInstance().postJson(ServiceUrl.getbuttonlimits, {
      "user_name":UserUtil.getUSER()?.userName
    }, (data) {
      DetailConfigEntity bannerEntity = DetailConfigEntity.fromJson(jsonDecode(data));
      // Constant.isBtnShow = bannerEntity.msg;
      Constant.fqkfText = bannerEntity.fqkfText;
      Constant.fqkf = bannerEntity.fqkf;
      Constant.SHARE_URL = bannerEntity.url;
      isKj = bannerEntity.iskj;
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }
  void _checkBuy(){
    DioManager.getInstance().post(ServiceUrl.checkBuy,{
      "user_name":UserUtil.getUSER()?.userName.toString(),
    }, (data) async {
      SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));

      if(bannerEntity.code==200){
        _buy();
      }else{
        ToastUtil.show(bannerEntity.msg);
      }
    }, (error) {
      ToastUtil.show(error);
    });
  }
  List<ServiceListData> fqList=[];
  List<ServiceListData> zxList=[];
  List<ServiceListData> ligmList=[];
  void _getServiceList(kf_type){
    DioManager.getInstance().post(ServiceUrl.serviceDetailList,{
      "channel_id":record_id,
      "kf_type":kf_type,
    }, (data) async {
      ServiceListEntity bannerEntity = ServiceListEntity.fromJson(jsonDecode(data));
      if(kf_type=='fqkf'){
        fqList = bannerEntity.data;
      }else if(kf_type=='zxkf'){
        zxList = bannerEntity.data;
      }else if(kf_type=='ljgm'){
        ligmList = bannerEntity.data;
        print("aaaaaaaaaa="+ligmList.length.toString());
      }
      if(bannerEntity.code==200){
      }else{
        // ToastUtil.show(bannerEntity.msg);
      }
    }, (error) {
      ToastUtil.show(error);
    });
  }


  late BuildContext mContext;
  void _buy(){
    showDialog(context: mContext, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){
          Navigator.pop(context1);
          DioManager.getInstance().post(ServiceUrl.buy,{
            "channel_id":detailData.channelId,
            "goods_id":detailData.id.toString(),
            "user_name":UserUtil.getUSER()?.userName.toString(),
            "buy_type":'3',

          }, (data) async {
            SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
            ToastUtil.show(bannerEntity.msg);
            if(bannerEntity.code==200){
              Get.off(()=>OrdersBuyPage(),arguments: 0);
              _getService();
            }else{

            }
          }, (error) {
            ToastUtil.show(error);
          });
        }
      },
        msg: "确认购买此商品吗？",
        sureText: "确定",
      );
    });
  }

  var cliclkBigIndex = 0;
  var currentBigIndex = 0.obs;
  bool showBig = false;
  onPageChanged(int a){
    currentBigIndex.value = a;
    // update();
  }

  copyLink(){
    if(!isInital){
      ToastUtil.show('未获取到数据');
      return;
    }
    // List<String> urls =Constant.SHARE_URL.split('?');
    String url = Constant.SHARE_URL+'goods_id='+detailData.id.toString()+'&channel_id='+detailData.channelId.toString()+'&channel_name='+detailData.channelName;
    print('urlurlurl==='+url);
    Clipboard.setData(ClipboardData(text: url));
    ToastUtil.show('链接已复制');
  }

  _getBPFee(){
    // double.parse(item.realityPrice)+20}元，包赔费用${().toStringAsFixed(2)
    double aa = double.parse(detailData.sellPrice) *baopeiRate.value;
    if(baopeiRate.value==0.1){
      if(aa<50){
        return 50;
      }
      return aa;
    }else {
      if(aa<100){
        return 100;
      }
      return aa;
    }
  }

  _getNum(){

   int index = detailData.title.indexOf("号");
   return  detailData.title.substring(0,index);
  }

}

class DetailPage extends GetView<DetailController>  {
  late DetailController controller ;
  late BuildContext context ;
  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<DetailController>(() => DetailController());
    controller = Get.find();
    context = context1;
    controller.mContext= context1;
    return GetBuilder<DetailController>(
      builder: (_){
        return  Scaffold(
            appBar: MyDetailAppBar(context: context, title: controller.isInital? controller.detailData.goodName:'商品详情',hasLeading: true,callBack: (str){
              controller.copyLink();
            },),
            backgroundColor: Colors.white,
            body: controller.isEmpty?_empty(): _content());
      },
    );
  }

  Widget _empty(){
    return Container(
      margin: EdgeInsets.only(top: 50.h),
      alignment: Alignment.center,
      child: Image.asset(Constant.IMG_BASE+'empty.png',width: 150.w,height: 127.h,),
    );
  }

  Widget _content(){

    print('_content_content_content');

    return !controller.isInital?Container():  Container(
      child:
      Stack(
        children: [
          SingleChildScrollView(
              child:    Column(
                children: [
                  _top(),
                  _line1(),
                  _protect(),
                  _line1(),
                  _tabs(),
                  controller.nowClick==0?
                  _desc():Container(),
                  controller.nowClick==1?
                  _desc2():Container(),
                  controller.nowClick==2?
                  _desc3():Container(),

                  SizedBox(height: 80.h,),
                ],
              )
          )
          ,

          Positioned(
              bottom: 0,
              child: _bottom())
        ],
      )

      ,);
  }

  Widget _top(){
    return Container(
      margin: EdgeInsets.only(left: 16.w,right: 16.w),
      child: Column(
        children: [
          _img(),
          _open(),
          _info(),


        ],
      ),
    );
  }

  Widget _img(){
    return  InkWell(
      onTap: (){
        showDialog(
            barrierColor: Colors.black,
            context: context,
            builder: (context) {
              return  _gallery();
            });
      },
      child:  Container(
        height: 148.h,
        margin: EdgeInsets.only(top: 11.h),
        width: MediaQuery.of(context).size.width - 32.w,
        child: ClipRRect(
            borderRadius: BorderRadius.circular(6.r),
            child: Image.network(controller.detailData.imgUrl,fit: BoxFit.fitWidth,)
        ) ,
      )
    );
  }

  Widget _open(){
    return Column(
      children: [
        _title(),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            InkWell(
                onTap: (){
                  controller.isOpenMore = !controller.isOpenMore;
                  controller.update();
                },
                child:  Text( controller.isOpenMore?'收起':'展开',style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp),)
            )

          ],
        )
      ],
    );
  }

  Widget _title(){
    return controller.isOpenMore? Container(
      child: Text(controller.detailData.title,style: TextStyle( fontWeight:FontWeight.w600,color: Color(0xFF333333),fontSize: 14.sp),
      ),
    ):
    Container(
      child: Text(controller.detailData.title,style: TextStyle( fontWeight:FontWeight.w600,color: Color(0xFF333333),fontSize: 14.sp),
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
      ),
    );
  }

  Widget _info(){
    return
      Container(
          margin: EdgeInsets.only(top: 8),
          padding: EdgeInsets.only(left: 12.w,top: 8.h,right: 12.w,bottom: 12.h),
          decoration: BoxDecoration(
            color: Color(0xFFFFFBF5),
          ),
          child:  Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text('售价：',style: TextStyle(color: Color(0xFF666666),fontSize: 12.sp),),
                  Text('¥',style: TextStyle(color: Color(0xFFFF0000),fontSize: 12.sp),),
                  Text(controller.detailData.sellPrice.toString(),style: TextStyle(color: Color(0xFFFF0000),fontSize: 18.sp),),
                ],
              ),
              SizedBox(height: 5.h,),
              Text('区服：${controller.detailData.categoryText}',style: TextStyle(color: Color(0xFF666666),fontSize: 12.sp,),textAlign:TextAlign.start),
              SizedBox(height: 5.h,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  // Text('营地号：54968788',style: TextStyle(color: Color(0xFF666666),fontSize: 12.sp),),
                  // Text('商品类型：官方自营',style: TextStyle(color: Color(0xFF666666),fontSize: 12.sp),),
                ],
              ),

              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  // Text('营地号：54968788',style: TextStyle(color: Color(0xFF666666),fontSize: 12.sp),),
                  Text('商品类型：${controller.detailData.isDeductible=='1'?'签约商家':'官方代售'}',style: TextStyle(color: Color(0xFF666666),fontSize: 12.sp),),
                ],
              ),
              SizedBox(height: 5.h,),
              // Text('商品编号：${controller.detailData.id}',style: TextStyle(color: Color(0xFF666666),fontSize: 12.sp),),
              Text('商品编号：${ controller. _getNum()}',style: TextStyle(color: Color(0xFF666666),fontSize: 12.sp),),

              // Container(child: controller.detailData.roleText.isEmpty?Container(): Text('失败原因：${controller.detailData.roleText}',style: TextStyle(color: Color(0xFF666666),fontSize: 12.sp),),)

            ],
          )
      )
    ;
  }

  Widget _line1(){
    return Container(
      margin: EdgeInsets.only(top: 18.h),
      width: MediaQuery.of(context).size.width,
      height: 6.h,
      color: Color(0xFFF7F8FC),
    );
  }

  Widget _protect(){
    return Container(
      margin: EdgeInsets.only(top: 13.h,left: 16.w,right: 16.w),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Text('商品保障：',style: TextStyle(color: Color(0xFF666666),fontSize: 13.sp),),
            ],
          ),
          SizedBox(height: 13.h,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Image.asset( '${Constant.IMG_BASE}icon_protect_y.png',width: 16.w,height: 16.h,),
                  SizedBox(width: 6.w,),
                  Text('可买包赔',style: TextStyle(color: const Color(0xFF666666),fontSize: 13.sp),)
                ],
              ),

              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Image.asset(controller.detailData.isMsg==0? '${Constant.IMG_BASE}icon_protect_n.png':'${Constant.IMG_BASE}icon_protect_y.png',width: 16.w,height: 16.h,),
                  SizedBox(width: 6.w,),
                  Text(    '可二次实名',style: TextStyle(color: Color(0xFF666666),fontSize: 13.sp),)
                ],
              ),

              Row(
                children: [
                  Image.asset(controller.detailData.isIndulge==0? '${Constant.IMG_BASE}icon_protect_y.png':'${Constant.IMG_BASE}icon_protect_n.png',width: 16.w,height: 16.h,),
                  SizedBox(width: 6.w,),
                  Text(  '无防沉迷',style: TextStyle(color: Color(0xFF666666),fontSize: 13.sp),)
                ],
              ),
            ],
          ),
          SizedBox(height: 13.h,),

        ],
      ),
    );
  }

  Widget _tabs(){
    return Container(
      height: 43.h,
      decoration: const BoxDecoration(
        color: Color(0xFFF5F5F5),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          _tabsItsm('商品介绍',0),    _tabsItsm('交易须知',1),    _tabsItsm('交流群',2),
        ],
      ),
    );
  }


  Widget _tabsItsm(name,index){
    return InkWell(
        onTap: (){
          controller.nowClick = index;
          controller.update();
        },
        child: Container(
            width: 99.w,
            height: 43.h,
            alignment: Alignment.center,
            decoration: const BoxDecoration(
              color: Color(0xFFF5F5F5),
            ),
            child:controller.nowClick==index?
            Container(
              height: 43.h,
              alignment: Alignment.center,
              decoration: const BoxDecoration(
                color: Colors.white,
                border: Border(top: BorderSide(width: 1, color: Color(0xFFF43F50))),
              ),
              child: Text(name,style: TextStyle(color: const Color(0xFF333333),fontSize: 13.sp),),
            ):Text(name,style: TextStyle(color: const Color(0xFF333333),fontSize: 13.sp))
        )
    ) ;
  }

  Widget _desc(){
    return Container(
        width: MediaQuery.of(context).size.width,
        margin: EdgeInsets.only(bottom: 80.h),
        child:  ListView.builder(
          shrinkWrap: true,
          physics: new NeverScrollableScrollPhysics(),
          itemBuilder: (context, index) {
            return _imgs(controller.detailData.albums[index].originalPath);
          },
          itemCount: controller.detailData.albums.length,
        )


      // Column(
      //   children:  controller.detailData.albums.map((item) => _imgs(item.originalPath)).toList()) ,
    );
  }

  Widget _imgs(String path){
    return InkWell(
        onTap: (){
          int index = 0;
          for(int i =0 ;i<controller.detailData.albums.length;i++) {
            if (controller.detailData.albums[i].originalPath == path) {
              index = i;
              break;
            }
          }
          controller.cliclkBigIndex = index;
          controller.showBig = true;
          controller.currentBigIndex.value = index;
          showDialog(
              barrierColor: Colors.black,
              context: context,
              builder: (context) {
                return  _gallery();
              });

          // showDialog(
          //     context: context,
          //     builder: (context) {
          //       return StatefulBuilder(
          //         builder: (context, state) {
          //           return MyGalleryDialog(defaultIndex: index,
          //               galleryItems: controller.detailData.albums,state:state,controller: controller,);
          //         },
          //       );
          //     });


        },
        child: Container(
          margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
          child: ClipRRect(
              borderRadius: BorderRadius.circular(6.r),
              child: CachedNetworkImage(imageUrl: path, imageBuilder: (context, imageProvider) => Container(
                  height: 130.h,
                  width: 328.w,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: imageProvider,
                      fit: BoxFit.fitWidth,
                    ),
                  )))

          ),
        )
    ) ;
  }

  Widget _gallerySingle(img){
    return   Container(
      height: Get.height - 30.h,
      width: Get.width,
      child: Material(
          color: Colors.black,
          type: MaterialType.transparency,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                  height: 300.h,
                  width: Get.width,
                  child:
                  Image.network(img,fit: BoxFit.fitWidth,)

              ),


            ],
          )
      )  ,
    ) ;
  }


  Widget _gallery(){
    return   Container(
      height: Get.height - 30.h,
      width: Get.width,
      child: Material(
        color: Colors.black,
          type: MaterialType.transparency,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                  height: 300.h,
                  width: Get.width,
                  child: PhotoViewGallery.builder(
                    scrollPhysics: const BouncingScrollPhysics(),
                    builder: (BuildContext context, int index) {
                      return PhotoViewGalleryPageOptions(
                        imageProvider: NetworkImage(Common.realPicPath(controller.detailData.albums[index].originalPath) ),
                        heroAttributes: PhotoViewHeroAttributes(tag: controller.detailData.albums[index].id),
                      );
                    },
                    itemCount: controller.detailData.albums.length,
                    backgroundDecoration:  BoxDecoration(color: Colors.black12),
                    pageController:  PageController(initialPage: controller.cliclkBigIndex),
                    onPageChanged: controller.onPageChanged,
                  )
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Obx(() =>
                      Text(
                        (controller.currentBigIndex.value+1).toString(),
                        style:
                        TextStyle(color: Colors.white),
                      ),
                  ),
                  Text(
                    '/'+controller.detailData.albums.length.toString(),style: TextStyle(color: Colors.white),)
                ],
              )


            ],
          )
      )  ,
    ) ;
  }


  Widget _desc2(){
    return Html(
      data: controller.xuzhi,
    );
  }

  // Widget _desc2(){
  //   return Container(
  //     width: MediaQuery.of(context).size.width,
  //     child: _process(),
  //   );
  // }

  Widget _process(){
    return Container(
      width: Get.width,
      child: Column(
        children: [
          Container(
              height: 50.h,
              margin: EdgeInsets.only(left: 10.w),
              child:  Row(
                  children:  controller.processData.map((item) => _processName(item)).toList())
          )
          ,
          _processDesc()
        ],
      ) ,
    );
  }

  Widget _processName(item){
    return InkWell(
        onTap: (){
          controller.clickProcessItem = item;
          controller.update();
        },
        child: Container(
          margin: EdgeInsets.only(right: 10.w),
          child:   Row(
            children: [
              controller.clickProcessItem['id'] == item['id']?
              Container(width: 2.w,height: 10.h,color: const Color(0xFFF43F50),):Container(),
              SizedBox(width: 5.w,),
              Text(item['title']),
            ],
          ),
        )
    );
  }

  Widget _processDesc(){
    return Container(
      padding: EdgeInsets.fromLTRB(10.w, 10.h, 10.w, 20.h),
      decoration: const BoxDecoration(
        color: Color(0xFFFFFBF5),
      ),
      child: Html( data:  controller.clickProcessItem['content'],),
    );
  }

  Widget _desc3(){
    return Container(
      margin: EdgeInsets.all(10.w),
      width: MediaQuery.of(context).size.width,
      child:  GridView.builder(
        shrinkWrap: true,
        itemCount: controller.groupData.length,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            mainAxisSpacing: 12,
            childAspectRatio:1 / 0.7
        ),
        itemBuilder: (_, position) => _groupItem(controller.groupData[position]),
      ),
    );
  }

  Widget _groupItem(GroupData item){
    return Container(
      decoration: const BoxDecoration(
          color: Color(0xffff7f8fc)
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(height: 7.h,),
          Text(item.type),
          SizedBox(height: 7.h,),
          Text(item.num),
          SizedBox(height: 9.h,),
          Container(
            alignment: Alignment.center,
            width: 98.w,
            height: 26.h,
            decoration: BoxDecoration(
                color: const Color(0xFFF43F50),
                borderRadius: BorderRadius.circular(21.r)
            ),
            child: const Text('立即加群',style: TextStyle(
                color: Colors.white
            ),),
          )
        ],
      ),
    );
  }


  Widget _bottom(){
    return
      Container(
          width: MediaQuery.of(context).size.width,
          alignment: Alignment.center,
          padding: EdgeInsets.only(left: 20.w,right: 10.w),
          height: 61.h,
          decoration: const BoxDecoration(
              color: Colors.white
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              InkWell(
                  onTap: (){
                    if(Common.checkLoginByMsg('收藏商品请先登录',context)){
                      controller._goodsCollect();
                    }
                  },
                  child:   Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Image.asset(controller.detailData.isShoucang?Constant.IMG_BASE+'icon_collect_y.png':Constant.IMG_BASE+'icon_collect_n.png',width: 16.w,height: 16.h,),

                      Text(controller.detailData.isShoucang?'已收藏':'收藏',style: TextStyle(
                          color: Color(0xFF666666),fontSize: 13.sp
                      ),)
                    ],
                  )
              )
              ,
              SizedBox(width: 1.w,),

              controller.isKj =='1' && controller.detailData.isBargain =='1'?
              InkWell(
                  onTap: (){
                    if(Common.checkLoginOrReal(context)){
                      Get.to(()=>KanjiaPage(),arguments:{
                        "channel_id":controller.detailData.channelId,
                        "goods_id":controller.detailData.id.toString(),
                        "price":controller.detailData.sellPrice,
                      },preventDuplicates:false );
                    }
                  },
                  child:   Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Image.asset('${Constant.IMG_BASE}icon_kanjia.png',width: 16.w,height: 16.h,),
                      Text('砍价',style: TextStyle(
                          color: Color(0xFF666666),fontSize: 13.sp
                      ),)
                    ],
                  )
              )
                  :Container()
              ,

              Row(
                children: [
                  InkWell(
                      onTap: (){
                        bool isSucc =  Common.checkLoginOrReal(
                            context
                        );
                        if(!isSucc){
                          return;
                        }
                        // Get.to(()=>ChatPage(),arguments: {
                        //   'sessionId':controller.imListData.account,
                        //   'nickName':controller.imListData.nickname,
                        //   'servicePhoto':controller.imListData.photo,
                        //   'info':controller.detailData
                        // },preventDuplicates:false);
                        if(controller.imList.length%2!=0){
                          DetailImData d = DetailImData();
                          d.account='-100';
                          controller.imList.add(d);
                        }
                        showDialog(
                            context: context,
                            builder: (context1) {
                              return StatefulBuilder(
                                builder: (context, state) {
                                  return Container(
                                    alignment: Alignment.bottomCenter,
                                    child: Material(
                                      color: Colors.transparent,
                                      child: showDialogContainer(state,context1,controller.imList),
                                    ),
                                  );
                                },
                              );
                            });

                      },
                      child: Container(
                        margin: EdgeInsets.only(left: 13.w),
                        alignment: Alignment.center,
                        width: 78.w,
                        height: 40.h,
                        decoration: BoxDecoration(
                            color: Color(0xFFFDA926),
                            borderRadius: BorderRadius.circular(6.r)
                        ),
                        child: Text('咨询客服',style: TextStyle(color: Colors.white,fontSize:13.sp ),),
                      )
                  ),
                  Constant.fqkf=='0'?Container():
                  InkWell(
                      onTap: (){
                        bool isSucc =  Common.checkLoginOrReal(
                            context
                        );
                        if(!isSucc){
                          return;
                        }
                        if(Constant.fqkf=='2'){
                          showDialog(
                              context: context,
                              builder: (context1) {
                                return StatefulBuilder(
                                  builder: (context, state) {
                                    return Container(
                                      alignment: Alignment.center,
                                      child: Material(
                                        color: Colors.transparent,
                                        child: showDialogContainer2(state,context1),
                                      ),
                                    );
                                  },
                                );
                              });
                        }else{
                          showDialog(
                              context: context,
                              builder: (context1) {
                                return StatefulBuilder(
                                  builder: (context, state) {
                                    return Container(
                                      alignment: Alignment.bottomCenter,
                                      child: Material(
                                        color: Colors.transparent,
                                        child: showDialogContainer(state,context1,controller.fqList),
                                      ),
                                    );
                                  },
                                );
                              });
                        }

                      },
                      child: Container(
                        margin: EdgeInsets.only(left: 7.w),
                        alignment: Alignment.center,
                        width: 78.w,
                        height: 40.h,
                        decoration: BoxDecoration(
                            color: Color(0xFF7D87FA),
                            borderRadius: BorderRadius.circular(6.r)
                        ),
                        child: Text('分期购买',style: TextStyle(color: Colors.white,fontSize:13.sp ),),
                      )
                  ),
                  InkWell(
                      onTap: (){
                        if( Common.checkLoginOrReal(context)){
                          print('controller.detailData.isDeductible=='+controller.detailData.isDeductible);
                          if(controller.detailData.isDeductible =='1'){
                            Get.off(()=>ChargePage(),arguments: {
                              'readOnly':true,
                              'price':controller.detailData.sellPrice,
                              'from':'buyNow',
                              'from_page':'detail',
                              "channel_id":controller.detailData.channelId,
                              "goods_id":controller.detailData.id.toString(),
                              "CompensationCode":'',
                            });
                          }
                          else if(Constant.isBtnShow == '0'){
                            _showSingle();
                          }else{

                          }
                        }

                      },
                      child: Container(
                        margin: EdgeInsets.only(left: 7.w),
                        alignment: Alignment.center,
                        width: 78.w,
                        height: 40.h,
                        decoration: BoxDecoration(
                            color: Color(0xFFF43F50),
                            borderRadius: BorderRadius.circular(6.r)
                        ),
                        child: Text('立即购买',style: TextStyle(color: Colors.white,fontSize:13.sp ),),
                      )
                  )
                  ,
                ],
              )

            ],
          )
      );
  }

  Widget showDialogContainer2(Function state,context1) {
    return
      Container(
        margin: EdgeInsets.all(20.w),
        // padding: EdgeInsets.fromLTRB(20.w, 0, 20.w, 0),
        width: Get.width - 40.w,
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(5.r)
        ),
        child:  Column(
          mainAxisSize:  MainAxisSize.min,
          children: [
            Stack(
              children: [
                Container(
                  margin: EdgeInsets.only(top: 10.h),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('提示',style: TextStyle(
                          color: Color(0xFF007BE5),
                          fontSize: 18.sp,
                        fontWeight: FontWeight.bold
                      ),),
                    ],
                  ),
                ),
                Container(
                  child:  Html(data: Constant.fqkfText),
                ),
              Positioned(
                top: 5.h,
                  right: 30.w,
                  width: 25.w,
                  height: 25.w,
                  child:   IconButton(
                onPressed: () {
                  Navigator.pop(context1);
                },
                icon: const Icon(
                  Icons.close,
                  color: Colors.grey,
                ),
              ))


    //             Positioned(bottom: 40,
    //               child: Container(
    //                 padding: EdgeInsets.only(left: 20.w,right: 20.w),
    //                   width: Get.width - 40.w,
    // child: Row(
    //   mainAxisAlignment: MainAxisAlignment.center,
    //   children: [
    //     InkWell(
    //         onTap: (){
    //           Navigator.pop(context1);
    //         },
    //         child:  Container(
    //           margin: EdgeInsets.only(right: 10.w),
    //           width: 80.w,
    //           height: 35.h,
    //           alignment: Alignment.center,
    //           decoration: BoxDecoration(
    //               borderRadius: BorderRadius.circular(10.r),
    //               color: Color(0xff3b8ce5)
    //           ),
    //           child: Text('确定',style: TextStyle(
    //               color: Colors.white,
    //               fontSize: 14.sp
    //           ),),
    //         )
    //     ),
    //     InkWell(
    //         onTap: (){
    //           Navigator.pop(context1);
    //         },
    //         child:Container(
    //           width: 80.w,
    //           height: 35.h,
    //           margin: EdgeInsets.only(left: 10.w),
    //           alignment: Alignment.center,
    //           decoration: BoxDecoration(
    //               borderRadius: BorderRadius.circular(10.r),
    //               color: Colors.white,
    //               border: Border.all(width: 1.w,color: Color(0xFFD6D6D6))
    //           ),
    //           child: Text('取消',style: TextStyle(
    //               color: Color(0xffadadad),
    //               fontSize: 14.sp
    //           ),),
    //         )
    //     )
    //     ,
    //
    //   ],
    // )
    // )  ,)
              ],
            )


          ],
        ),

      );
  }

  Widget showDialogContainer(Function state,context1,list) {
    return
      Container(
          width: Get.width,
          color: Colors.white,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(height: 14.h,),
              InkWell(
                  onTap: (){
                    Navigator.pop(context1);
                  },
                  child: Container(
                    padding: EdgeInsets.all(14.h),
                    width: 80.w,
                    height: 4.h,
                    decoration: BoxDecoration(
                        color: Color(0xFF007BE5),
                        borderRadius: BorderRadius.circular(2.r)
                    ),
                  )
              )
              ,
              SizedBox(height: 14.h,),
              Wrap(
                alignment: WrapAlignment.spaceBetween,
                crossAxisAlignment: WrapCrossAlignment.start,
                  direction: Axis.horizontal,
                children: List.generate(list.length, (index) => _item(list[index],index,context1)),
              )
            ],
          ));
  }


  Widget _item(DetailImData item,index,context1){
    return item.account=='-100'?Container(
      width: 151.w,
      height: 108.h,
      margin: EdgeInsets.only(left: index%2==0?0: 4.w,right: index%2==0?4.w: 0,bottom: 6.w),)
        :
    Container(
      width: 151.w,
      height: 108.h,
      margin: EdgeInsets.only(left: index%2==0?0: 4.w,right: index%2==0?4.w: 0,bottom: 6.w),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16.r),
          border: Border.all(color: Color(0xFFF4F4F4))
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text('${item.nickname}',style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: 13.sp
              ),),
              SizedBox(width: 2.w,),
              item.account==
              UserUtil.getService()?Text('最近咨询',style: TextStyle(
                color: Colors.red,
                fontSize: 11.sp
              ),):Container()
            ],
          )
         ,
          SizedBox(height: 10.h,),
          item.isRest==0?
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              ClipOval(
                child: Container(
                  color: Color(0xFFFF9800),
                  width: 7.w,
                  height: 7.w,
                ),
              ),
              SizedBox(width: 5.w,),
              Text('在线',style: TextStyle(
                  fontSize: 13.sp,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFFFF9800)
              ),)
            ],
          )
              :
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              ClipOval(
                child: Container(
                  color: Color(0xFFBBBBBB),
                  width: 7.w,
                  height: 7.w,
                ),
              ),
              SizedBox(width: 5.w,),
              Text('休息',style: TextStyle(
                  fontSize: 13.sp,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFFBBBBBB)
              ),)
            ],
          )
          ,
          SizedBox(height: 12.h,),
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              InkWell(
                  onTap: (){
                    if(Common.checkLoginOrReal(context)){
                      Navigator.pop(context1);
                      UserUtil.saveService(item.account);
                      Get.to(()=>ChatPage(),arguments: {
                        'sessionId':item.account,
                        'nickName':item.nickname,
                        'servicePhoto':item.photo,
                        'info':controller.detailData
                      },preventDuplicates:false);

                    }

                  },
                  child: item.isRest==0?

                  Container(
                    alignment: Alignment.center,
                    width: 84.w,
                    height: 21.h,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(21.r),
                        color: Color(0xFF02D85F)
                    ),
                    child: Text('联系客服',style: TextStyle(
                        color: Colors.white,
                        fontSize: 10.sp
                    ),),
                  ):
                  Container(
                    alignment: Alignment.center,
                    width: 84.w,
                    height: 21.h,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(21.r),
                        color: Color(0xFFBBBBBB)
                    ),
                    child: Text('联系客服',style: TextStyle(
                        color: Colors.white,
                        fontSize: 10.sp
                    ),),
                  )
              )



            ],
          )

        ],
      ),
    );
  }


  Future<Future<int?>> _showSingle() async {
    return showModalBottomSheet<int>(
        backgroundColor: Colors.transparent,
        isScrollControlled: true,
        context: context,
        builder: (BuildContext context1) {
          return AnimatedPadding(
              padding: MediaQuery.of(context1).viewInsets, // 我们可以根据这个获取需要的padding
              duration: const Duration(milliseconds: 100),
              child:  Container(
                  height: 350.h,
                  padding: EdgeInsets.all(16.w),
                  clipBehavior: Clip.antiAlias,
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(20.0),
                      topRight: Radius.circular(20.0),
                    ),
                  ),
                  child: Column(
                    children: [
                      Text('选择包赔类型',style: TextStyle(
                          color: Color(0xFF333333),
                          fontSize: 15.sp
                      ),),
                      SizedBox(height: 15.h,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Image.asset( '${Constant.IMG_BASE}item_new.png',width: 24.w,height: 17.h,),
                              Text('普通包赔10%',style: TextStyle(
                                  color: Color(0xFF333333),
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.bold
                              ),)
                            ],
                          ),
                          Obx(() => InkWell(
                            onTap: (){
                              controller.baopeiRate.value = 0.1;
                              controller.update();
                            },
                            child:
                            controller.baopeiRate.value==0.1?
                            Image.asset( '${Constant.IMG_BASE}radio_yy.png',width: 18.w,height: 18.h,): Image.asset( '${Constant.IMG_BASE}icon_protect_n.png',width: 18.w,height: 18.h,),
                          )),


                        ],
                      ),
                      SizedBox(height: 10.h,),
                      Text('在下单购买账号时额外支付号价的10% (最低50元)，购买交易完成后，账号不转手 (换绑手机视为转手) 永久享受包赔服务，如出现账号找回情况，平台核实后在七天内进行处理，优先追回账号，超过七天未追回将全额退还支付号款，并对找回人员进行起诉追责处理!',
                        style: TextStyle(
                            color: Color(0xFF666666),
                            fontSize: 13.sp
                        ),),

                      SizedBox(height: 15.h,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Image.asset( '${Constant.IMG_BASE}item_new.png',width: 24.w,height: 17.h,),
                              Text('2.5包赔20%',style: TextStyle(
                                  color: Color(0xFF333333),
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.bold
                              ),)
                            ],
                          ),
                          Obx(() => InkWell(
                            onTap: (){
                              controller.baopeiRate.value = 0.2;
                              controller.update();
                            },
                            child:
                            controller.baopeiRate.value==0.2?
                            Image.asset( '${Constant.IMG_BASE}radio_yy.png',width: 18.w,height: 18.h,): Image.asset( '${Constant.IMG_BASE}icon_protect_n.png',width: 18.w,height: 18.h,),
                          )),


                        ],
                      ),
                      SizedBox(height: 10.h,),
                      Text('在下单购买账号时额外支付号价的20% (最低100元)，交易完成后，账号不转手 (换绑手机视为转手) 永久享受2.5倍包赔服务，如出现账号找回情况，平台核实后在七天内进行处理，优先追回账号，超过七天未追回将全额退还支付号款，并对找回人员进行起诉追责处理!',
                        style: TextStyle(
                            color: Color(0xFF666666),
                            fontSize: 13.sp
                        ),),
                      SizedBox(height: 10.h,),
                      Container(
                        width: Get.width,
                        color: Color(0x0D000000),
                        height: 1.h,
                      ),
                      Container(
                          alignment: Alignment.center,
                          height: 53.h,
                          child:    Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Obx(() => Text('号价为${controller.detailData.sellPrice}元，包赔费用${(controller._getBPFee()).toStringAsFixed(2)}元',style: TextStyle(
                                  color: Color(0xFFFF0000),
                                  fontSize: 14.sp
                              ),))
                              ,
                              InkWell(
                                  onTap: (){
                                    double aa = double.parse(controller.detailData.sellPrice) + controller._getBPFee();
                                    Get.off(()=>ChargePage(),arguments: {
                                      'readOnly':true,
                                      'price':aa.toStringAsFixed(2),
                                      'from':'buyNow',
                                      "channel_id":controller.detailData.channelId,
                                      "goods_id":controller.detailData.id.toString(),
                                      "CompensationCode":controller.baopeiRate.value==0.1?'ordinaryBP':'twoFiveBP',
                                    });
                                  },
                                  child: Container(
                                    alignment: Alignment.center,
                                    width: 104.w,
                                    height: 31.h,
                                    decoration: BoxDecoration(
                                        color: Color(0xFF007BE5),
                                        borderRadius: BorderRadius.all(Radius.circular(16.r))
                                    ),
                                    child: Text('立即支付',style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 13.sp
                                    ),),
                                  )
                              )


                            ],
                          )
                      )

                    ],
                  )
              )
          ) ;
        });
  }

}